import 'package:flutter/material.dart';
import 'package:flutter_module/animation/frames_animation.dart';
import 'package:get/get.dart';

class RootController extends GetxController {
  List<Widget> pages = [];

  int currentIndex = 0;

  //记录当前选中item的索引
  int lastIndex = 0;

  //存放帧动画组件的key
  List<GlobalKey<FramesAnimationState>> frameKeys = [];

  /// PageView的控制器
  PageController? pageController;

  @override
  void onInit() {
    super.onInit();
    // 创建PageView的控制器
    pageController = PageController();
  }

  // @override
  // void onClose() {
  //   super.onClose();
  //   // 重置变量到初始值,无效
  //   currentIndex = 0;
  //   lastIndex = 0;
  // }

  void initList(List<Widget> targetPages,
      List<GlobalKey<FramesAnimationState>> targetFrameKeys,int currentIndex,int lastIndex) {
    pages = targetPages;
    frameKeys = targetFrameKeys;
    this.currentIndex = currentIndex;//currentIndex和lastIndex需要进行初始化，否则会存在问题。在onInit和onClose中进行设置无效，具体原因不明。
    this.lastIndex = lastIndex;
  }

  void switchItem(int index) {
    if (lastIndex == index) {
      return;
    }

    //启动本次被选中item的帧动画
    frameKeys[index].currentState?.startAnimation();
    //重置上一次被选中item的帧动画
    frameKeys[lastIndex].currentState?.resetAnimation();
    //记录本次被选中的item索引
    lastIndex = index;

    // 控制页面切换
    pageController!.jumpToPage(index);

    currentIndex = index;
    update();
  }

  getFramesAnimation(int index, String iconPath) => FramesAnimation(
      key: frameKeys[index],
      initIndex: index,
      images: loadImageFrames(iconPath));

  /// 加载帧动画图片
  List<Image> loadImageFrames(String path) {
    List<Image> images = [];
    for (var i = 0; i < 24; i++) {
      images.add(Image.asset(
        'assets/' + path + '_$i.png',
        width: 20.0,
        height: 20.0,
        gaplessPlayback: true,
      ));
    }
    return images;
  }
}
